import os
from email.parser import Parser

rootdir = "/home/shzhuoyu/downloads/maildir/"

def email_analyse(inputfile,body_list):
    with open(inputfile, "r", encoding='utf-8') as f:
        try:
            data = f.read()
        except:
            with open(inputfile, "r", encoding='ISO-8859-1') as f:
                data = f.read()
    email= Parser().parsestr(data)
    if email.get_payload():
        email_body = email.get_payload()
        body_list.append(email_body)

body_list = []
for directory, subdirectory, filenames in  os.walk(rootdir):
    print('now in: '+directory)
    for filename in filenames:
        email_analyse(os.path.join(directory, filename),body_list)

print(body_list)
with open("body.txt", "w") as f:
    for item in body_list:
        if item:
            f.write(item)
            f.write("\n")

